package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"v8s/metrics"

	"v8s-ssp-proxy/internal/types"
)

func (c *controller) handleStatus(ctx context.Context, msg types.SSPPartnerMessage) error {
	return metrics.WithOperation("status", "v8s", "ssp-proxy", func() error {
		resources := make([]types.ResourceStatus, 0, len(msg.ResourceIds))

		for _, resourceID := range msg.ResourceIds {
			if parts := strings.Split(resourceID, ":"); len(parts) >= resourceIDValuesCount {
				task, err := c.handlers.GetTask(ctx, resourceID)
				if err != nil {
					c.log.Errorf("failed to get task '%s' status: %s", resourceID, err)
					continue
				}

				resources = append(resources, types.ResourceStatus{
					ResourceId:     resourceID,
					ResourceStatus: string(task.Status),
				})
			}
		}

		b, err := json.Marshal(types.ResourceResponse{Resources: resources})
		if err != nil {
			return fmt.Errorf("marshal response error: %w", err)
		}

		if len(resources) == 0 {
			return nil
		}

		c.writer.WriteMsg(msg.RqUUID, resourceStatusHeader, resourceStatusHeaderValue, b)

		return nil
	})
}
